import _ from "lodash";
import React, { PropsWithChildren, RefObject, useEffect, useRef } from "react";
import Blockly, { BlocklyOptions } from 'blockly'
import './index.css'

const BlocklyComponent = ()=>{
    const blocklyDiv = React.createRef<HTMLDivElement>();
    const blocklyArea = React.createRef<HTMLDivElement>();
    let workspace: Blockly.WorkspaceSvg | null=null;
    const toolbox = {
  "kind": "flyoutToolbox",
  "contents": [
    {
      "kind": "block",
      "type": "controls_if"
    },
    {
      "kind": "block",
      "type": "controls_repeat_ext"
    },
    {
      "kind": "block",
      "type": "logic_compare"
    },
    {
      "kind": "block",
      "type": "math_number"
    },
    {
      "kind": "block",
      "type": "math_arithmetic"
    },
    {
      "kind": "block",
      "type": "text"
    },
    {
      "kind": "block",
      "type": "text_print"
    },
    ]
}
    const resize = _.debounce(() => {
    // if (blocklyDiv.current && blocklyDiv.current.parentElement instanceof HTMLElement) {
    //   blocklyDiv.current.style.width = `${blocklyDiv.current.parentElement.offsetWidth}px`;
    //   blocklyDiv.current.style.height = `${blocklyDiv.current.parentElement.offsetHeight}px`;
    // }
    // if (workspace) Blockly.svgResize(workspace);
    let element = blocklyArea.current;
    var x = 0;
    var y = 0;
    if(element)
    {
        x += element.offsetLeft;
        y += element.offsetTop;
    }
    // Position blocklyDiv over blocklyArea.
    if(blocklyDiv.current&&blocklyArea.current)
    {
        blocklyDiv.current.style.left = x + 'px';
        blocklyDiv.current.style.top = y + 'px';
        blocklyDiv.current.style.width = blocklyArea.current.offsetWidth + 'px';
        blocklyDiv.current.style.height = blocklyArea.current.offsetHeight + 'px';
    }
    if(workspace)
    {
        Blockly.svgResize(workspace);
    }
  }, 0)
  useEffect(()=>{
    window.addEventListener('resize', resize, false);
        // if(blocklyDiv.current){
        //      workspace = Blockly.inject(
        //         blocklyDiv.current,{
        //             toolbox:toolbox
        //         }
        //     )
        // }
        // resize();
    }) 

    
    return(
        <>
        <div ref={blocklyArea} className="blockly-container" id="blocklyArea" style={{ position: 'relative' }}>
            {/* <div className="blocklyDiv" ref={blocklyDiv} style={{position:"absolute"}}>
            </div> */}
        </div>
        </>
    )
}
export default BlocklyComponent;